#pragma once
#include<iostream>
#include<sys/epoll.h>
#include "Log.hpp"
#include "Common.hpp"

using namespace LogModule;

class Epoller
{
public:
    Epoller():_epfd(-1)
    {
        _epfd = epoll_create(128);
        if(_epfd < 0)
        {
            LOG(LogLevel::FATAL) << "epfd create fail";
            exit(EPOLL_CREATE_ERR);
        }
        LOG(LogLevel::INFO) << "epfd create success:" << _epfd;
    }

    void ModEventHelper(int sockfd,uint32_t events,int oper)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = sockfd;
        int n = epoll_ctl(_epfd,oper,sockfd,&ev);
        if(n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            exit(EPOLL_CTL_ERR);
        }
        LOG(LogLevel::INFO) << "epoll_ctl success:" << sockfd;
    }

    void AddEvent(int sockfd,uint32_t events)
    {
        ModEventHelper(sockfd,events,EPOLL_CTL_ADD);
    }

    void ModEvent(int sockfd,uint32_t events)
    {
        ModEventHelper(sockfd,events,EPOLL_CTL_MOD);
    }

    void DelEvent(int sockfd)
    {
        int n = epoll_ctl(_epfd,EPOLL_CTL_DEL,sockfd,nullptr);
        (void)n;
    }

    int WaitEvents(struct epoll_event revs[],int maxnum,int timeout)
    {
        int n = epoll_wait(_epfd,revs,maxnum,timeout);
        if(n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_wait error";
        }
        else if(n == 0)
        {
            LOG(LogLevel::INFO) << "epoll_wait timeout";
        }
        else
        {
            //说明revs队列中已经有就绪的事件了，返回n让上层去处理
        }
        return n;
    }

    ~Epoller()
    {
        if(_epfd >= 0)
            close(_epfd);
    }
private:
    int _epfd;
};
